package com.hxzy.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.exception.WaimaiException;
import com.hxzy.dto.mapstruct.LoginBeanConvert;
import com.hxzy.dto.req.back.LoginDTO;
import com.hxzy.dto.resp.AdminLoginVO;
import com.hxzy.entity.Employee;
import com.hxzy.mapper.EmployeeMapper;
import com.hxzy.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * 业务逻辑实现类
 * @Service 必须要加，代码交给框架来管理（业务逻辑）
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<Employee, BigDecimal> implements EmployeeService {

    private EmployeeMapper  employeeMapper;

    /**
     * 交给spring框架自动装配需要的类
     * @param employeeMapper
     */
    @Autowired
    public void setEmployeeMapper(EmployeeMapper employeeMapper) {
        this.employeeMapper = employeeMapper;
        //不要忘记给父类赋值
        super.setMyBatisBaseDao(employeeMapper);
    }

    @Override
    public AdminLoginVO login(LoginDTO loginDTO) {
        Employee db=this.employeeMapper.findByName(loginDTO.getLoginName());
        if(Objects.isNull(db)){
            throw new WaimaiException(AckCode.USERNAME_PASSWORD_ERROR);
        }

        if(!BCrypt.checkpw(loginDTO.getLoginPwd(), db.getLoginPwd())){
            throw new WaimaiException(AckCode.USERNAME_PASSWORD_ERROR);
        }

        if(db.getStatus().intValue()==1){
            throw new WaimaiException(AckCode.DEVICE_BANNED);
        }

        //复制对象(不推荐的，比较复杂)
  //      AdminLoginVO  adminLoginVO=new AdminLoginVO();
//        adminLoginVO.setId(db.getId());
//        adminLoginVO.setLoginName(db.getLoginName());
//        adminLoginVO.setLoginPwd(db.getLoginPwd());
//        adminLoginVO.setAvatar(db.getAvatar());
//        adminLoginVO.setUserType(1);

        //方案2,工具，反射技术，进行两个对象中的属性名称相同，就进行COPY，坏处，性能比较差的
       // BeanUtils.copyProperties(db,adminLoginVO );

        //方案3: MapStruct
       AdminLoginVO adminLoginVO= LoginBeanConvert.INSTANCE.employeeToAdminLoginVO(db);
       adminLoginVO.setUserType(1);
        return adminLoginVO;
    }
}
